package com.augmentum.oes.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.augmentum.oes.controller.UserController;
import com.augmentum.oes.dao.mybatis.UserDaoImpl;
import com.augmentum.oes.exception.ParameterException;
import com.augmentum.oes.exception.ServiceException;
import com.augmentum.oes.model.User;
import com.augmentum.oes.service.UserService;
import com.augmentum.oes.util.MD5Util;
import com.augmentum.oes.util.MessageUtils;
import com.augmentum.oes.util.StringUtil;

@Service
public class UserServiceImpl implements UserService {
    /**
     * Login service
     * 
     * @param userName
     * @param password
     * @return
     */
    private final String REGEX1 = "^([A-Za-z0-9]{2,16}$)|(^[\u4E00-\u9FA5]{2,8})$";
    private final String REGEX2 = "^[0-9_a-zA-Z]{6,20}$";
    private static final Logger log = Logger.getLogger(UserController.class);
    @Autowired
    private UserDaoImpl userDao;

    public User login(String userName, String password) {
        long start = System.currentTimeMillis();
        User user = userDao.getInfo(userName);
        Map<String, String> errorMap = new HashMap<>();
        String newPassword = null;
        newPassword = MD5Util.encryption(password);
        if (StringUtil.isEmpty(userName) || !userName.matches(REGEX1)) {
            errorMap.put("userName",
                    MessageUtils.buildMessage(MessageUtils.REQUIRED_FIELD_ERROR, "userName", MessageUtils.ENTITY_USER));
        }
        if (StringUtil.isEmpty(password) || !password.matches(REGEX2)) {
            errorMap.put("password",
                    MessageUtils.buildMessage(MessageUtils.REQUIRED_FIELD_ERROR, "password", MessageUtils.ENTITY_USER));
        }
        if (!errorMap.isEmpty()) {
            // Check parameter
            throw new ParameterException(MessageUtils.ENTITY_NOT_FOUND, MessageUtils.buildMessage(
                    MessageUtils.ENTITY_NOT_FOUND, MessageUtils.ENTITY_USER), errorMap);
        }

        if (user == null || !newPassword.equals(user.getPassword())) {
            // Check password
            throw new ServiceException(MessageUtils.ENTITY_NOT_FOUND, MessageUtils.buildMessage(
                    MessageUtils.ENTITY_NOT_FOUND, MessageUtils.ENTITY_USER));
        }
        long end = System.currentTimeMillis();
        log.info(end - start);
        return user;
    }
}
